/**
 * PLM项目Store
 * 实现PLM项目列表的状态管理
 * 项目内部实现，与全局保持一致
 */

// 引入必要的工具库，使用统一配置入口
const { cloudHelper } = require('../config/project_helpers_config');
const { dateHelper, statusHelper } = require('../config/project_helpers_config');
const { dayjs } = require('../config/libs_config');
const { observable, action, computed } = require('mobx-miniprogram');

// 引入数据一致性检查工具
const { dataConsistencyChecker } = require('../../../helpers/data_consistency_checker');

// 尝试导入全局项目store作为基础
let globalPlmProjectStore = null;
try {
  globalPlmProjectStore = require('../store/modules/project/plm_project_store');
  console.log('成功导入全局plm_project_store');
} catch (e) {
  console.warn('导入全局plm_project_store失败，使用本地实现', e);
}

// 静态状态映射表，避免依赖this上下文
const PROJECT_STATUS_MAP = {
  0: '草稿',
  1: '待立项',
  2: '已立项',
  3: '设计中',
  4: '开发中',
  5: '测试中',
  6: '已完成',
  99: '已取消'
};

// 静态获取状态文本的函数，不依赖this
function getStatusTextStatic(status) {
  return PROJECT_STATUS_MAP[status] || '未知状态';
}

// 分支LRU缓存配置
const BRANCH_CACHE_CONFIG = {
  maxAge: 5 * 60 * 1000, // 5分钟
  maxSize: 100
};
const branchCache = new Map();
function updateBranchCache(branchId, data) {
  if (branchCache.size >= BRANCH_CACHE_CONFIG.maxSize) {
    const oldestKey = branchCache.keys().next().value;
    branchCache.delete(oldestKey);
  }
  branchCache.set(branchId, { data, timestamp: Date.now() });
}

// 一致性检查增强
function checkBranchConsistency(currentBranch, currentProject) {
  if (currentBranch && currentProject) {
    if (currentBranch.level1 !== currentProject.level1 ||
        currentBranch.level2 !== currentProject.level2) {
      // 可自动同步或提示
      // this.syncBranchState && this.syncBranchState();
      console.warn('分支状态与项目状态不一致');
    }
  }
}

// 创建PLM项目Store
// 如果已存在全局store，则扩展它；否则创建新的
const plmProjectStore = observable(globalPlmProjectStore || {
  // 项目列表
  projectList: [],
  
  // 当前项目
  currentProject: null,
  
  // 当前分支
  currentBranch: null,
  
  // 可用分支列表
  branchList: [],
  
  // 加载状态
  loading: false,
  
  // 错误消息
  error: null,
  
  // 缓存相关
  cache: {
    projectList: null,
    projectDetail: new Map(),
    branchList: new Map(),
    lastUpdate: null
  },
  
  // 数据一致性检查器
  consistencyChecker: dataConsistencyChecker,
  
  // 加载项目列表
  loadProjectList: action(async function(params = {}) {
    console.log('[PLM项目Store] 加载项目列表', params);
    this.loading = true;
    this.error = null;
    
    // 检查是否强制从云端获取
    const forceCloud = params.forceCloud === true;
    if (forceCloud) {
      console.log('[PLM项目Store] 强制从云端获取数据');
    }
    
    try {
      // 检查缓存是否有效（只有在非强制云端模式下才使用缓存）
      const cacheKey = JSON.stringify(params);
      if (!forceCloud && 
          this.cache.projectList && 
          this.cache.lastUpdate && 
          Date.now() - this.cache.lastUpdate < 5 * 60 * 1000) { // 5分钟缓存
        console.log('[PLM项目Store] 使用缓存的项目列表');
        this.projectList = this.cache.projectList;
        this.loading = false;
        return { list: this.projectList, total: this.projectList.length };
      }
      
      const options = {
        title: '加载中...',
        hasLoading: true,
        forceCloud: forceCloud === true, // 确保是布尔值true
        useOfflineData: !forceCloud, // 如果forceCloud为true，则禁用离线数据
        showError: true
      };
      
      console.log('[PLM项目Store] 请求选项:', options);
      
      const result = await cloudHelper.callCloudData('mcloud', {
        route: 'project_list',
        page: params.page || 1,
        size: params.size || 20,
        ...this.filters,
        ...params,
        PID: 'plm' // 显式指定PID为plm
      }, options);
      
      // 安全检查：确保result存在且包含list属性
      if (!result) {
        console.warn('[PLM项目Store] 服务器返回结果为空');
        this.loading = false;
        return { list: [], total: 0 };
      }
      
      // 确保数据结构一致性
      let projectList = [];
      let total = 0;
      
      // 适配不同的数据返回格式
      if (result.list) {
        // 直接返回了list
        projectList = result.list;
        total = result.total || 0;
      } else if (result.data && result.data.list) {
        // 返回了data包装层
        projectList = result.data.list;
        total = result.data.total || 0;
      } else {
        // 其他格式，尝试提取
        projectList = Array.isArray(result) ? result : [];
        total = projectList.length;
      }
      
      // 格式化项目数据
      if (params.page === 1 || !params.page) {
        // 第一页，替换数据
        this.projectList = projectList.map(item => this.formatProject(item));
        // 更新缓存
        this.cache.projectList = this.projectList;
        this.cache.lastUpdate = Date.now();
      } else {
        // 分页加载，追加数据
        this.projectList = [...this.projectList, ...projectList.map(item => this.formatProject(item))];
      }
      
      this.pagination = {
        page: params.page || 1,
        size: params.size || 20,
        total: total,
        hasMore: this.projectList.length < total
      };
      
      // 检查数据一致性
      if (this.consistencyChecker && typeof this.consistencyChecker.checkProjectConsistency === 'function') {
        this.consistencyChecker.checkProjectConsistency();
      }
      
      this.loading = false;
      return { list: this.projectList, total: total };
    } catch (error) {
      this.error = error.message || '加载项目列表失败';
      this.loading = false;
      console.error('[PLM项目Store] 加载项目列表失败:', error);
      
      // 返回安全的默认结果，而不是抛出错误
      return { 
        list: [], 
        total: 0,
        page: params.page || 1,
        size: params.size || 20 
      };
    }
  }),
  
  // 加载项目详情
  loadProjectDetail: action(async function(id) {
    console.log('[PLM项目Store] 加载项目详情', id);
    if (!id) {
      this.error = '项目ID不能为空';
      return;
    }
    
    this.loading = true;
    this.error = null;
    
    try {
      // 检查缓存是否有效
      if (this.cache.projectDetail.has(id)) {
        const cachedDetail = this.cache.projectDetail.get(id);
        if (Date.now() - cachedDetail.timestamp < 5 * 60 * 1000) { // 5分钟缓存
          console.log('[PLM项目Store] 使用缓存的项目详情');
          this.currentProject = cachedDetail.data;
          this.loading = false;
          return this.currentProject;
        }
      }
      
      const options = {
        title: '加载中...',
        hasLoading: true
      };
      
      // 获取项目详情
      const result = await cloudHelper.callCloudData('mcloud', { 
        route: 'project_detail',
        id
      }, options);
      
      if (!result || !result.data) {
        throw new Error('获取项目详情失败');
      }
      
      // 获取项目分支信息
      const branchResult = await cloudHelper.callCloudData('mcloud', {
        route: 'project/branch/list',
        projectId: id,
        PID: 'plm'
      }, options);
      
      // 格式化项目数据
      this.currentProject = this.formatProject(result.data);
      
      // 更新缓存
      this.cache.projectDetail.set(id, {
        data: this.currentProject,
        timestamp: Date.now()
      });
      
      // 处理分支数据
      if (branchResult && Array.isArray(branchResult.list)) {
        this.branchList = branchResult.list.map(branch => ({
          ...branch,
          name: branch.name || branch.BRANCH_NAME || '未命名分支',
          createTimeFormatted: dateHelper.timestampToDate(branch.CREATE_TIME || branch.createTime)
        }));
        
        // 更新分支缓存
        this.cache.branchList.set(id, {
          data: this.branchList,
          timestamp: Date.now()
        });
        
        // 设置当前分支
        if (this.currentProject.branchId) {
          this.currentBranch = this.branchList.find(b => b._id === this.currentProject.branchId) || null;
        } else if (this.branchList.length > 0) {
          // 默认选择第一个分支（通常是主分支）
          this.currentBranch = this.branchList[0];
        }
      }
      
      // 检查数据一致性
      this.consistencyChecker.checkProjectConsistency();
      
      this.loading = false;
      return this.currentProject;
    } catch (error) {
      this.error = error.message || '加载项目详情失败';
      this.loading = false;
      console.error('[PLM项目Store] 加载项目详情失败:', error);
      throw error;
    }
  }),
  
  // 切换分支
  switchBranch: action(async function(branchId) {
    if (!branchId || !this.currentProject) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 查找选中的分支
      const branch = this.branchList.find(b => b._id === branchId);
      if (!branch) {
        throw new Error('分支不存在');
      }
      
      const options = {
        title: '切换分支中...',
        hasLoading: true
      };
      
      // 调用API切换分支
      const result = await cloudHelper.callCloudData('mcloud', { 
        route: 'project/branch/switch',
        projectId: this.currentProject._id,
        branchId: branchId,
        PID: 'plm'
      }, options);
      
      if (!result || !result.data) {
        throw new Error('切换分支失败');
      }
      
      // 更新当前分支
      this.currentBranch = branch;
      
      // 更新项目的分支相关信息
      this.currentProject = {
        ...this.currentProject,
        branchId: branch._id,
        branchName: branch.name,
        level1: result.data.level1,
        level2: result.data.level2,
        level3: result.data.level3,
        level4: result.data.level4,
        completionPercentage: result.data.completionPercentage || 0
      };
      
      // 更新缓存
      this.cache.projectDetail.set(this.currentProject._id, {
        data: this.currentProject,
        timestamp: Date.now()
      });
      
      // 检查数据一致性
      this.consistencyChecker.checkProjectConsistency();
      
      this.loading = false;
      return this.currentProject;
    } catch (error) {
      this.error = error.message || '切换分支失败';
      this.loading = false;
      console.error('[PLM项目Store] 切换分支失败:', error);
      
      // 尝试从缓存恢复
      try {
        const cachedDetail = this.cache.projectDetail.get(this.currentProject._id);
        if (cachedDetail) {
          console.log('[PLM项目Store] 从缓存恢复项目数据');
          this.currentProject = cachedDetail.data;
          this.currentBranch = this.branchList.find(b => b._id === this.currentProject.branchId) || null;
        }
      } catch (recoveryError) {
        console.error('[PLM项目Store] 缓存恢复失败:', recoveryError);
      }
      
      throw error;
    }
  }),
  
  // 创建新分支
  createBranch: action(async function(branchData) {
    if (!this.currentProject) {
      throw new Error('没有当前项目');
    }
    
    this.loading = true;
    this.error = null;
    
    try {
      const options = {
        title: '创建分支中...',
        hasLoading: true
      };
      
      // 调用API创建分支
      const result = await cloudHelper.callCloudData('mcloud', {
        route: 'project/branch/create',
        projectId: this.currentProject._id,
        ...branchData,
        PID: 'plm'
      }, options);
      
      if (!result || !result.data) {
        throw new Error('创建分支失败');
      }
      
      // 添加新分支到列表
      const newBranch = {
        ...result.data,
        name: result.data.name || '未命名分支',
        createTimeFormatted: dateHelper.timestampToDate(result.data.createTime)
      };
      
      this.branchList = [...this.branchList, newBranch];
      
      // 更新分支缓存
      this.cache.branchList.set(this.currentProject._id, {
        data: this.branchList,
        timestamp: Date.now()
      });
      
      this.loading = false;
      return newBranch;
    } catch (error) {
      this.error = error.message || '创建分支失败';
      this.loading = false;
      console.error('[PLM项目Store] 创建分支失败:', error);
      throw error;
    }
  }),
  
  // 删除分支
  deleteBranch: action(async function(branchId) {
    if (!this.currentProject || !branchId) {
      throw new Error('参数错误');
    }
    
    this.loading = true;
    this.error = null;
    
    try {
      const options = {
        title: '删除分支中...',
        hasLoading: true
      };
      
      // 调用API删除分支
      const result = await cloudHelper.callCloudData('mcloud', {
        route: 'project/branch/delete',
        projectId: this.currentProject._id,
        branchId: branchId,
        PID: 'plm'
      }, options);
      
      if (!result || !result.success) {
        throw new Error('删除分支失败');
      }
      
      // 从列表中移除分支
      this.branchList = this.branchList.filter(b => b._id !== branchId);
      
      // 如果删除的是当前分支，切换到主分支
      if (this.currentBranch && this.currentBranch._id === branchId) {
        const masterBranch = this.branchList.find(b => b.isMaster);
        if (masterBranch) {
          await this.switchBranch(masterBranch._id);
        } else if (this.branchList.length > 0) {
          await this.switchBranch(this.branchList[0]._id);
        } else {
          this.currentBranch = null;
        }
      }
      
      // 更新分支缓存
      this.cache.branchList.set(this.currentProject._id, {
        data: this.branchList,
        timestamp: Date.now()
      });
      
      this.loading = false;
      return true;
    } catch (error) {
      this.error = error.message || '删除分支失败';
      this.loading = false;
      console.error('[PLM项目Store] 删除分支失败:', error);
      throw error;
    }
  }),
  
  // 合并分支
  mergeBranch: action(async function(sourceBranchId, targetBranchId) {
    if (!this.currentProject || !sourceBranchId || !targetBranchId) {
      throw new Error('参数错误');
    }
    
    this.loading = true;
    this.error = null;
    
    try {
      const options = {
        title: '合并分支中...',
        hasLoading: true
      };
      
      // 调用API合并分支
      const result = await cloudHelper.callCloudData('mcloud', {
        route: 'project/branch/merge',
        projectId: this.currentProject._id,
        sourceBranchId: sourceBranchId,
        targetBranchId: targetBranchId,
        PID: 'plm'
      }, options);
      
      if (!result || !result.success) {
        throw new Error('合并分支失败');
      }
      
      // 重新加载分支列表
      const branchResult = await cloudHelper.callCloudData('mcloud', {
        route: 'project/branch/list',
        projectId: this.currentProject._id,
        PID: 'plm'
      }, options);
      
      if (branchResult && Array.isArray(branchResult.list)) {
        this.branchList = branchResult.list.map(branch => ({
          ...branch,
          name: branch.name || branch.BRANCH_NAME || '未命名分支',
          createTimeFormatted: dateHelper.timestampToDate(branch.CREATE_TIME || branch.createTime)
        }));
        
        // 更新分支缓存
        this.cache.branchList.set(this.currentProject._id, {
          data: this.branchList,
          timestamp: Date.now()
        });
      }
      
      this.loading = false;
      return true;
    } catch (error) {
      this.error = error.message || '合并分支失败';
      this.loading = false;
      console.error('[PLM项目Store] 合并分支失败:', error);
      throw error;
    }
  }),
  
  // 错误恢复机制
  recoverFromError: action(async function() {
    console.log('[PLM项目Store] 尝试从错误中恢复');
    
    try {
      // 1. 清理错误状态
      this.error = null;
      
      // 2. 如果有当前项目，尝试重新加载
      if (this.currentProject) {
        await this.loadProjectDetail(this.currentProject._id);
      }
      
      // 3. 重新加载项目列表
      await this.loadProjectList();
      
      // 4. 检查数据一致性
      this.consistencyChecker.checkProjectConsistency();
      
      return true;
    } catch (error) {
      console.error('[PLM项目Store] 错误恢复失败:', error);
      this.error = '恢复失败: ' + (error.message || '未知错误');
      return false;
    }
  }),
  
  // 清理当前项目
  clearProject: action(function() {
    console.log('[PLM项目Store] 清理当前项目');
    this.currentProject = null;
    this.currentBranch = null;
    this.branchList = [];
  }),
  
  // 清理所有数据
  clearAll: action(function() {
    console.log('[PLM项目Store] 清理所有数据');
    this.projectList = [];
    this.currentProject = null;
    this.currentBranch = null;
    this.branchList = [];
    this.loading = false;
    this.error = null;
  }),
  
  // 状态定义
  pagination: { page: 1, size: 20, total: 0, hasMore: true },
  filters: {
    status: 'all',
    keyword: '',
    cate: 0,
    devManager: 0,
    bizManager: 0
  },
  
  // 计算属性
  get filteredProjects() {
    return this.projectList;
  },
  
  get projectCount() {
    return this.projectList.length;
  },
  
  // 获取分支选项计算属性
  get branchOptions() {
    return this.branchList.map((branch, index) => ({
      id: branch._id,
      name: branch.name,
      index
    }));
  },
  
  // 获取当前分支索引计算属性
  get currentBranchIndex() {
    if (!this.currentBranch || !this.branchList.length) return 0;
    return this.branchList.findIndex(b => b._id === this.currentBranch._id);
  },
  
  // 行为方法
  async getProjectList(params = {}) {
    return this.loadProjectList(params);
  },
  
  async loadMoreProjects() {
    if (!this.pagination.hasMore || this.loading) return false;
    
    const nextPage = this.pagination.page + 1;
    return this.loadProjectList({ page: nextPage });
  },
  
  setFilters: action(function(filters) {
    this.filters = {
      ...this.filters,
      ...filters
    };
    
    // 重置分页
    this.pagination.page = 1;
  }),
  
  clearAllCache: action(function() {
    console.log('[PLM项目Store] 清理所有缓存');
    this.projectList = [];
    this.currentProject = null;
    this.currentBranch = null;
    this.branchList = [];
    this.pagination = { page: 1, size: 20, total: 0, hasMore: true };
    this.error = null;
    
    // 清理缓存
    this.cache = {
      projectList: null,
      projectDetail: new Map(),
      branchList: new Map(),
      lastUpdate: null
    };
  }),
  
  // 格式化项目数据
  formatProject(project) {
    if (!project) return null;
    
    // 清理不需要的字段
    const cleanedProject = { ...project };
    
    // 删除旧字段
    const oldFields = ['id', 'projectTitle', 'statusText', 'statusDesc', 
                       'startDateStr', 'deadlineStr', 'planStartDateStr', 'planEndDateStr'];
    
    oldFields.forEach(field => {
      if (field in cleanedProject) {
        delete cleanedProject[field];
      }
    });
    
    // 确保必要字段存在，设置默认值
    cleanedProject._id = cleanedProject._id || '';
    cleanedProject.model = cleanedProject.model || '未命名项目';
    
    // 计算和格式化字段
    const formatted = {
      ...cleanedProject,
      _id: cleanedProject._id || '',
      model: cleanedProject.model || cleanedProject.name || '未命名项目',
      
      // 状态处理
      fullStatusDesc: statusHelper ? statusHelper.getFullStatusDesc(cleanedProject) : 
                     (PROJECT_STATUS_MAP[cleanedProject.level1] || '未知状态'),
      
      // 格式化日期
      startDateFormatted: dateHelper ? 
        dateHelper.timestampToDate(cleanedProject.startDate || cleanedProject.PROJECT_START_DATE) : 
        this._formatDate(cleanedProject.startDate || cleanedProject.PROJECT_START_DATE),
      
      deadlineFormatted: dateHelper ? 
        dateHelper.timestampToDate(cleanedProject.deadline || cleanedProject.PROJECT_DEADLINE) : 
        this._formatDate(cleanedProject.deadline || cleanedProject.PROJECT_DEADLINE),
        
      planStartDateFormatted: dateHelper ? 
        dateHelper.timestampToDate(cleanedProject.planStartDate || cleanedProject.PROJECT_PLAN_START_DATE) : 
        this._formatDate(cleanedProject.planStartDate || cleanedProject.PROJECT_PLAN_START_DATE),
        
      planEndDateFormatted: dateHelper ? 
        dateHelper.timestampToDate(cleanedProject.planEndDate || cleanedProject.PROJECT_PLAN_END_DATE) : 
        this._formatDate(cleanedProject.planEndDate || cleanedProject.PROJECT_PLAN_END_DATE),
      
      // 计算进度颜色
      progressColor: this._calculateProgressColor(cleanedProject),
      
      // 计算距截止日期天数
      daysTillDeadline: this._calculateDaysTillDeadline(cleanedProject),
      
      // 确保branchId和branchName存在
      branchId: cleanedProject.branchId || cleanedProject.BRANCH_ID || '',
      branchName: cleanedProject.branchName || cleanedProject.BRANCH_NAME || '主分支',
      
      // 确保level3和level4存在并正确初始化
      level3: cleanedProject.level3 || cleanedProject.PROJECT_ACTIVE_STATUS || '',
      level4: cleanedProject.level4 || cleanedProject.PROJECT_SUB_ACTIVE_STATUS || '',
      
      // 计算developmentStatus
      developmentStatus: cleanedProject.developmentStatus || this._calculateDevelopmentStatus(cleanedProject)
    };
    
    return formatted;
  },
  
  // 计算项目开发状态
  _calculateDevelopmentStatus(project) {
    if (!project) return '未知状态';
    
    // 如果项目已经包含developmentStatus字段，直接使用
    if (project.developmentStatus) {
      return project.developmentStatus;
    }
    
    // 根据状态计算开发状态
    const level1 = project.level1 || 0;
    const level2 = project.level2 || '';
    const level3 = project.level3 || '';
    const level4 = project.level4 || '';
    const completionPercentage = project.completionPercentage || 
                                project.PROJECT_PROGRESS || 0;
    
    // 状态到开发状态的映射逻辑
    if (level1 === 1) {
      return '待立项';
    } else if (level1 === 2) {
      return '休眠状态';
    } else if (level1 === 3) { // 活动状态
      // 根据二级状态细分
      if (level2 === 'planning') {
        return '规划中';
      } else if (level2 === 'design') {
        // 进一步细分设计阶段
        if (level3) {
          if (level3.includes('requirement')) return '需求分析中';
          if (level3.includes('schematic')) return '原理图设计中';
          if (level3.includes('pcb')) return 'PCB设计中';
          if (level3.includes('bom')) return 'BOM制定中';
          if (level3.includes('review')) return '设计评审中';
          if (level3.includes('completed')) return '设计已完成';
        }
        return '设计中';
      } else if (level2 === 'development') {
        // 进一步细分开发阶段
        if (level3) {
          if (level3.includes('hardware')) return '硬件开发中';
          if (level3.includes('firmware')) return '固件开发中';
          if (level3.includes('software')) return '软件开发中';
          if (level3.includes('prototype')) return '样机制作中';
          if (level3.includes('debug')) return '调试中';
          if (level3.includes('review')) return '开发评审中';
          if (level3.includes('completed')) return '开发已完成';
        }
        return '开发中';
      } else if (level2 === 'testing') {
        // 进一步细分测试阶段
        if (level3) {
          if (level3.includes('planning')) return '测试计划中';
          if (level3.includes('functional')) return '功能测试中';
          if (level3.includes('performance')) return '性能测试中';
          if (level3.includes('reliability')) return '可靠性测试中';
          if (level3.includes('emc')) return 'EMC测试中';
          if (level3.includes('safety')) return '安全测试中';
          if (level3.includes('certification')) return '认证测试中';
          if (level3.includes('field')) return '现场测试中';
          if (level3.includes('report')) return '测试报告中';
          if (level3.includes('review')) return '测试评审中';
          if (level3.includes('completed')) return '测试已完成';
        }
        return '测试中';
      } else if (level2 === 'validation') {
        // 进一步细分验证阶段
        if (level3) {
          if (level3.includes('planning')) return '验证计划中';
          if (level3.includes('batch')) return '小批量生产中';
          if (level3.includes('quality')) return '质量验证中';
          if (level3.includes('process')) return '工艺验证中';
          if (level3.includes('customer')) return '客户验证中';
          if (level3.includes('report')) return '验证报告中';
          if (level3.includes('review')) return '验证评审中';
          if (level3.includes('completed')) return '验证已完成';
        }
        return '验证中';
      }
      return '开发中'; // 默认开发中
    } else if (level1 === 4) {
      return '暂停状态';
    } else if (level1 === 5) {
      return '延期状态';
    } else if (level1 === 6) {
      return '搁置状态';
    } else if (level1 === 99) {
      return '已完成';
    }
    
    // 根据完成度的备用逻辑
    if (completionPercentage >= 100) {
      return '已完成';
    } else if (completionPercentage > 0) {
      return '开发中';
    }
    
    return '待开始';
  },
  
  // 格式化日期
  _formatDate(timestamp) {
    if (!timestamp) return '';
    try {
      return dayjs.unix(timestamp).format('YYYY-MM-DD');
    } catch (e) {
      return '';
    }
  },
  
  // 计算项目进度颜色
  _calculateProgressColor(project) {
    const progress = project.completionPercentage || project.PROJECT_PROGRESS || 0;
    if (progress < 30) return '#ff5252'; // 红色
    if (progress < 70) return '#ffb74d'; // 橙色
    return '#4caf50'; // 绿色
  },
  
  // 计算距截止日期天数
  _calculateDaysTillDeadline(project) {
    const deadline = project.deadline || project.PROJECT_DEADLINE;
    if (!deadline) return null;
    
    try {
      const now = dayjs();
      const deadlineDate = dayjs.unix(deadline);
      return deadlineDate.diff(now, 'day');
    } catch (e) {
      return null;
    }
  },
  
  // 创建空的项目对象
  createEmptyProject() {
    const now = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
    return {
      model: '',
      projectType: '霍尔',
      customerName: '',
      description: '',
      priority: 'normal',
      startDate: now,
      deadline: now + 86400 * 30, // 30天后
      level1: 1, // 默认为待立项状态
      level2: 'director',
      completionPercentage: 0,
      branchName: '主分支'
    };
  },
  
  // 格式化分支数据
  formatBranch(branch) {
    if (!branch) return null;
    
    const statusHelper = require('../helpers/status_helper');
    const { dayjs } = require('../config/libs_config');
    
    // 确保关键字段存在
    const formatted = {
      ...branch,
      _id: branch._id || '',
      branchId: branch._id || branch.branchId || '',
      branchName: branch.name || branch.branchName || '未命名分支',
      level1: branch.level1 || branch.status?.level1 || 1,
      level2: branch.level2 || branch.status?.level2 || 'director',
      level3: branch.level3 || branch.status?.level3 || null,
      level4: branch.level4 || branch.status?.level4 || null,
      
      // 计算状态描述
      fullStatusDesc: statusHelper.getFullStatusDesc({
        level1: branch.level1 || branch.status?.level1 || 1,
        level2: branch.level2 || branch.status?.level2 || 'director',
        level3: branch.level3 || branch.status?.level3 || null,
        level4: branch.level4 || branch.status?.level4 || null
      }),
      
      // 其他计算字段
      completionPercentage: branch.completionPercentage || 0,
      isActive: branch.active === undefined ? true : !!branch.active,
      isMaster: branch.isMaster === undefined ? false : !!branch.isMaster,
      
      // 格式化日期
      createTimeFormatted: branch.createTime ? dayjs.unix(branch.createTime).format('YYYY-MM-DD') : '',
      lastUpdateTimeFormatted: branch.lastUpdateTime ? dayjs.unix(branch.lastUpdateTime).format('YYYY-MM-DD') : ''
    };
    
    // 计算开发状态
    formatted.developmentStatus = statusHelper.getDevelopmentStatus(formatted);
    
    // 计算进度条颜色
    formatted.progressColor = statusHelper.getProgressColor(formatted);
    
    return formatted;
  },
  
  // 加载项目详情并合并分支数据
  async loadProjectDetailWithBranch(id, branchId = null) {
    // 1. 加载项目基本信息
    const project = await this.loadProjectDetail(id);
    if (!project) return null;
    
    // 2. 如果未指定分支ID，加载主分支
    const branchService = require('../services/branch_service');
    let branch;
    
    if (branchId) {
      // 加载指定分支
      branch = await branchService.getBranchDetail(branchId);
    } else {
      // 加载主分支
      branch = await branchService.getProjectMasterBranch(id);
    }
    
    // 3. 如果没有找到分支，直接返回项目信息
    if (!branch) return project;
    
    // 4. 合并项目和分支数据
    const mergedData = branchService.getBranchDataMapping(project, branch);
    
    return mergedData;
  }
});

// 导出模块
module.exports = plmProjectStore; 